<template>
  <div>
    <div class="mainCon">
      <div class="containercontent">

        <div class="seachTip selectw100">
          <div class="inlineblock verticalmiddle searchitem">
            <div class="inlineblock verticalmiddle">
              样品状态
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="sampleStateValue" placeholder="请选择" size="mini" @change="readTaskSample(sampleQuery,'search')">
                <el-option v-for="item in sampleState" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </div>

          </div>
          <div class="inlineblock verticalmiddle searchitem">
            <div class="inlineblock verticalmiddle">
              任务
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="taskListValue" size="mini" filterable @change="readTaskSample(sampleQuery,'search')" clearable @focus="readAllTask">
                <el-option v-for="item in taskList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="inlineblock verticalmiddle searchitem">
            <div class="inlineblock verticalmiddle">
              采样人
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="collectManValue" size="mini" filterable @change="readTaskSample(sampleQuery,'search')" clearable>
                <el-option v-for="item in userData" :key="item.account" :label="item.name" :value="item.account" >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon" style="margin-left:10px;">
            <el-button size="mini" @click="readTaskSample(sampleQuery,'search')">搜索</el-button>
            <el-button size="mini" @click="emptySearch()">清空</el-button>
          </div>
        </div>
        <div class="separaterowTable">
          <div class="tableTittle">
            <div><span class="fontImpact">1</span><span>采样登记</span></div>
            <!--v-if="sampleStateValue == '1'"-->
            <el-tooltip class="item" effect="dark" content="只作用于本页勾选的样品" placement="bottom">
              <el-button type="primary" size="mini" @click="registrateMore" style="float:right" v-if="sampleStateValue == '1' && userOpernation.register.display">样品登记</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="只作用于本页勾选的样品" placement="bottom">
              <el-button type="primary" size="mini" @click="printSample" style="float:right;margin:0 5px;" v-if="sampleStateValue == '1' && userOpernation.print.display">打印样品标签</el-button>
            </el-tooltip>
              <el-button type="primary" size="mini" style="float:right;" @click="downLoadExcel" v-if="sampleStateValue == '1' && userOpernation.download.display">下载采样记录表</el-button>



          </div>
          <!--v-if="sampleStateValue == '1'"-->
          <el-table :data="sampleTableDate" style="width: 100%" class="tableCon" size="mini" ref="multipleTable" @selection-change="handleSelectionChange"
            key="sampleTable">
            <el-table-column type="selection" width="38px" key="selection" v-if="sampleStateValue == '1'">
            </el-table-column>
            <el-table-column label="序号" min-width="50px">
              <template slot-scope="scope">
                {{scope.$index+(sampleQuery.page - 1) * sampleQuery.pageCount + 1}}
              </template>
            </el-table-column>
            <el-table-column property="name" label="样品名称" min-width="140px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column property="code" label="样品编号" min-width="140px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column property="taskName" label="任务名称" :show-overflow-tooltip="true" min-width="100px">
            </el-table-column>
            <el-table-column property="collectionDate" label="采样时间" :formatter="formatterDate" min-width="100px">
              <template slot-scope="scope">
                {{scope.row.collectionDate == "" || scope.row.collectionDate == undefined  ? '---':scope.row.collectionDate}}
              </template>
            </el-table-column>
            <el-table-column property="collectionManName" label="采样人" min-width="80px">
              <template slot-scope="scope">
                {{scope.row.collectionManName == "" || scope.row.collectionManName == undefined  ? '---':scope.row.collectionManName}}
              </template>
            </el-table-column>
            <el-table-column property="collectionLeaderName" label="现场负责人" min-width="80px">
              <template slot-scope="scope">
                {{scope.row.collectionLeaderName == "" || scope.row.collectionLeaderName == undefined  ? '---':scope.row.collectionLeaderName}}
              </template>
            </el-table-column>
            <el-table-column property="status" label="状态" min-width="80px" :formatter="formatterStatus">
            </el-table-column>
            <el-table-column v-if="sampleStateValue == '2'" label="登记人" property="registerName" :key="Math.random()" min-width="80px">
              <template slot-scope="scope">
                {{scope.row.registerName == "" || scope.row.registerName == undefined  ? '---':scope.row.registerName}}
              </template>
            </el-table-column>
            <el-table-column v-if="sampleStateValue == '2'" property="registerDate" label="登记时间" :formatter="formatterDate" :key="Math.random()"
              min-width="100px">
            </el-table-column>
            <el-table-column label="操作" v-if="sampleStateValue == '1'" :key="Math.random()"  min-width="90px">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="editSample(scope.row)" v-if="userOpernation.update.display">编辑</el-button>
                <!--<el-button type="text" size="mini" @click="editSample(scope.row)">详情</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <div class="block changepages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="sampleQuery.page" :page-sizes="[20, 30, 40]"
              :page-size="sampleQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="registraDetailShow" width="70%" :show-close='false' class="sampleDialog" :closeOnClickModal='false'>
      <span slot="title" class="dialog-title">
        样品登记
        <el-button  size="mini" class="popupClose" @click="close">关闭</el-button>
      </span>
      <el-table :data="registData" style="width: 100%;height:100%;" class="tableCon" size="mini" v-if="reload">
        <el-table-column property="code" label="编号" min-width="100px">
        </el-table-column>
        <el-table-column property="name" label="样品名称" min-width="100px" show-overflow-tooltip>
        </el-table-column>
        <el-table-column property="factDate" label="实际采样时间" :formatter="formatterDate" min-width="165px">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.factDate" type="datetime" size="mini" style="width:100%;" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择时间" :picker-options="pickerenddatefanwei">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column property="collectionMan" label="实际采样人" width="180px">
          <template slot-scope="scope">
            <!--readUsercollectionManName   factManName 实际采样人默认采样人 可修改-->
            <el-select v-model="scope.row.collectionMan" style="width:100px;" size="mini" filterable remote :remote-method="readUser"
              @focus="mouseoverHH1(scope.row)">
              <el-option v-for="item in userData" :key="item.account" :label="item.name" :value="item.account" :disabled="item.disabled">
              </el-option>
            </el-select>
            <el-button v-if="scope.row.piluru1" type="text" size="mini" @click="piluru1(scope.row,scope.$index)" class="buttonPiluru">批量</el-button>
            <!--<el-input size="mini" v-model="scope.row.factManName" placeholder=""></el-input>-->
          </template>
        </el-table-column>
        <el-table-column property="propertyOne" label="性状" min-width="150px">
          <template slot-scope="scope">
            <el-input @focus="mouseoverHH(scope.row)" size="mini" style="width:100px;" v-model="scope.row.propertyOne" placeholder=""></el-input>
            <el-button v-if="scope.row.piluru" type="text" size="mini" @click="piluru(scope.row,scope.$index)" class="buttonPiluru">批量</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="subRegisDetail" size="mini" :disabled="!isRepeat">提 交</el-button>
			    <el-button  size="mini" @click="close">取 消</el-button>
			  </span>
    </el-dialog>
    <sample-print :addVisible.sync="printTableShow" :multipleSelection.sync="multipleSelection" :acceptOrregist="acceptOrregist"></sample-print>
    <edit-sample :addVisible.sync="editSampleShow" :sampleInfo="sampleInfo"></edit-sample>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  const registraDetail = () => import('./children/registraDetail.vue');
  const samplePrint = () => import('./children/samplePrint.vue');
  const editSample = () => import('./children/editSample.vue');

  export default {
    data() {
      let that = this;
      return {
        sampleTableDate: [],//样品列表数据
        //样品状态 1 待登记 2是全部
        sampleState: [{
          code: 1,
          name: '待登记'
        }, {
          code: 2,
          name: '全部'
        }],
        rowNumber: 0, //列表总条数
        sampleQuery: {
          page: 1,
          pageCount: 20,
        },
        userInfo: {}, //用户信息
        sampleStateValue: 1, //搜索栏样品状态绑定值
        taskList: [], //任务列表
        taskListValue: '', // 搜索栏任务绑定值
        collectManValue: JSON.parse(sessionStorage.getItem('laboratoryAccountInfo')).loginid, //搜索栏采样人绑定值
        multipleSelection: [], //当页勾选的数据
        multipleSelectionAll: [], //勾选的所有数据

        registData: [], //选中的要进行登记的样品
        registraDetailShow: false,//样品登记弹框
        userData: [], //人员数据
        breakFlag: 1, //是否中断提交
        editSampleShow: false, //编辑样品弹框
        sampleInfo: {},
        reload: true,
        reload1: true,
        printTableShow: false,
        acceptOrregist: 'regist',
        isRepeat: true,
        receptModuleId: "", //样品接收模块id
        pickerenddatefanwei: {
          disabledDate: function (time) {
            let timeSpace = time.getTime() > new Date().getTime();
            return timeSpace;
          }
        },

      }
    },
    props: ["userOpernation"],
    components: {
      registraDetail, samplePrint, editSample
    },
    computed: {
      ...mapState(['enableStatus', 'taskSampleStatus', 'functionTableDate']),
      sampleTypeTable() {
        let that = this;
        return that.$common.objToArr(that.sampleType);
      }
    },
    created() {
      this.readTaskSample(this.sampleQuery);
      this.readUser('')
      this.userInfo = JSON.parse(sessionStorage.getItem('laboratoryAccountInfo'));
      // 调用公共函数 传 样品接收 的模块路由取对应的模块id
      this.receptModuleId = this.util.getModuleId({ module: "samplereception" })

    },
    watch: {
      sampleQuery: {
        handler(val, oldVal) {
          this.readTaskSample(this.sampleQuery)
        },
        deep: true
      },
    },
    methods: {
      // 清空搜索栏
      emptySearch() {
        // this.sampleStateValue = ''; //搜索栏样品状态绑定值
        this.taskListValue = '';
        this.collectManValue = '';
        this.readTaskSample(this.sampleQuery, 'search');
      },
      // 处理采样日期
      formatterDate(row, column, cellValue) {
        return this.util.formatterDate({ cellValue: cellValue })
      },
      // 处理状态
      formatterStatus(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.taskSampleStatus })
      },
      // changeSampleState(val){
      //   this.readTaskSample(this.sampleQuery);
      //   var step = null;
      //   if(val == 1){
      //     step = 1;
      //   }
      //   this.readAllTask(step)
      // },
      // 搜索栏搜索任务下拉框
      readAllTask() {
        var step = null
        if (this.sampleStateValue == 1) {
          step = 1
        }
        this.$http({
          method: 'post',
          apiUrl: '/detection/readAllTask.htm',
          params: {
            // name: item,
            step: step,
          },
          isJson: false
        }).then(res => {
          if (res.code === 0) {
            this.taskList = res.data
          }

        })
      },
      //读取采样登记列表
      readTaskSample(parp, search) {
        var params = {
          task: this.taskListValue,
          queryStatus: this.sampleStateValue,
          collectionMan: this.collectManValue,
        }
        if (search != undefined) {
          this.sampleQuery.page = 1;
          params.page = 1;
          params.pageCount = parp.pageCount;
        } else {
          params.page = parp.page;
          params.pageCount = parp.pageCount;
        }
        this.$http({
          method: 'post',
          apiUrl: '/detection/readTaskSampleBylab.htm',
          params: params,
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            for (var i in res.data) {
              res.data[i].factMan = this.userInfo.loginid;
              res.data[i].factManName = this.userInfo.name;

              // res.data[i].propertyOne ='';
              res.data[i].piluru = false;
              res.data[i].piluru1 = false;
              res.data[i].factDate = this.util.date() + " " + "00:00:00";
            }
            this.sampleTableDate = res.data;
            // console.log(this.multipleSelectionAll)
            setTimeout(() => {
              this.setSelectRow();
            }, 50)

            if (!res.pageinfo) {
              this.rowNumber = 0;
            } else if (res.pageinfo && !res.pageinfo.rowNumber) {
              this.rowNumber = 0;
            } else {
              this.rowNumber = res.pageinfo.rowNumber;
            }
          }

        })
      },
      // 编辑样品
      editSample(row) {
        this.editSampleShow = true;
        this.sampleInfo = {};
        for (var i in row) {
          this.sampleInfo[i] = row[i]
        }

      },
      // 选中列表的样品
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.reLoad1();
        setTimeout(() => {
          this.changePageCoreRecordData();
        }, 50)

      },
      setSelectRow() {
        if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
          return;
        }
        // 标识当前行的唯一键的名称
        let idKey = "id";
        let selectAllIds = [];
        let that = this;
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey]);
        })
        this.$refs.multipleTable.clearSelection();
        for (var i = 0; i < this.sampleTableDate.length; i++) {
          if (selectAllIds.indexOf(this.sampleTableDate[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="multipleTable"
            this.$refs.multipleTable.toggleRowSelection(this.sampleTableDate[i], true);
          }
        }
      },
      changePageCoreRecordData() {
        // 标识当前行的唯一键的名称
        let idKey = 'id';
        let that = this;
        // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
        if (this.multipleSelectionAll.length <= 0) {
          this.multipleSelectionAll = this.multipleSelection;
          return;
        }
        // 总选择里面的key集合
        let selectAllIds = [];
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey]);
        })
        let selectIds = []
        // 获取当前页选中的id
        this.multipleSelection.forEach(row => {
          selectIds.push(row[idKey]);
          // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
          if (selectAllIds.indexOf(row[idKey]) < 0) {
            that.multipleSelectionAll.push(row);
          }
        })
        let noSelectIds = [];
        // 得到当前页没有选中的id
        this.sampleTableDate.forEach(row => {
          if (selectIds.indexOf(row[idKey]) < 0) {
            noSelectIds.push(row[idKey]);
          }
        })
        noSelectIds.forEach(id => {
          if (selectAllIds.indexOf(id) >= 0) {
            for (let i = 0; i < that.multipleSelectionAll.length; i++) {
              if (that.multipleSelectionAll[i][idKey] == id) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.multipleSelectionAll.splice(i, 1);
                break;
              }
            }
          }
        })
      },
      //  选中样品 点击登记弹出框
      registrateMore() {
        // console.log(this.multipleSelection)
        if (this.multipleSelection.length == 0) {
          this.$notify({
            type: 'warning',
            message: '请先选中样品!',
            title:"警告"
          });
        } else {
          this.registraDetailShow = true;
          for (var i in this.multipleSelection) {
            this.$set(this.multipleSelection[i], 'propertyOne', null)
          }
          this.registData = JSON.parse(JSON.stringify(this.multipleSelection))
          // 获取样品接收的模块id  样品接收路由 samplereception
        }
      },
      //  是否重加载
      reLoad() {
        this.reload = false;
        this.$nextTick(() => {
          this.reload = true;
        })
      },
      reLoad1() {
        this.reload1 = false;
        this.$nextTick(() => {
          this.reload1 = true;
        })
      },
      // 批量设置数据
      piluru(row, index) {
        for (var i in this.registData) {
          if (this.registData[i].propertyOne == '' || this.registData[i].propertyOne == null) {
            this.registData[i].propertyOne = row.propertyOne;
          }
          this.reLoad()
          // if(i > index){
          //   newarr[i].propertyOne = row.propertyOne;
          //   newarr[i].factDate = row.factDate;
          //   newarr[i].factManName  = row.factManName;
          // }

        }

      },
      // 鼠标方在输入框 批量按钮出现
      mouseoverHH(row) {
        let newarr = this.registData;
        for (var i = 0; i < newarr.length; i++) {
          if (newarr[i] != row) {
            newarr[i].piluru = false;
          } else {
            row.piluru = true;
          }
        }
      },
      // 批量设置数据
      piluru1(row, index) {
        for (var i in this.registData) {
          if (this.registData[i].collectionMan == '' || this.registData[i].collectionMan == null) {
            this.registData[i].collectionMan = row.collectionMan;
          }
          this.reLoad()
        }

      },
      // 鼠标方在输入框 批量按钮出现
      mouseoverHH1(row) {
        let newarr = this.registData;
        for (var i = 0; i < newarr.length; i++) {
          if (newarr[i] != row) {
            newarr[i].piluru1 = false;
          } else {
            row.piluru1 = true;
          }
        }
      },
      // 读取用户
      readUser(item) {
        this.$http({
          method: 'post',
          apiUrl: '/resource/readEmployeeByLab.htm',
          params: { name: item },
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.userData = res.data;
          }

        })
      },
      // 验证标准系列不为空
      isNotNull(str, msg) {
        if (str == "" || str == undefined) {
          this.$message({
            type: 'info',
            message: msg + "不能为空！"
          })
          this.breakFlag = 0;
        } else {
          this.breakFlag = this.breakFlag * 1;
          return str;
        }
      },
      // 提交登记
      subRegisDetail() {
        this.breakFlag = 1;
        var newArr = [];
        for (var i in this.registData) {
          var data = {};
          data.id = this.registData[i].id;
          data.factMan = this.registData[i].collectionMan;
          for (var j in this.userData) {
            if (this.registData[i].collectionMan == this.userData[j].account) {
              data.factManName = this.userData[j].name;
            }
          }
          data.status = 511;  //点击登记,修改样品状态为待接收511
          data.factDate = this.isNotNull(this.registData[i].factDate, '采样日期');
          data.propertyOne = this.isNotNull(this.registData[i].propertyOne, '性状');
          data.moduleId = this.receptModuleId; //提交时传样品接收模块id 以及审核按钮权限标志
          data.operation = "receive";
          newArr.push(data);
        }
        if (this.breakFlag == 0) {
          return;
        }
        this.isRepeat = false;
        this.$http({
          method: 'post',
          apiUrl: '/detection/updateSamplesBycollect.htm',
          params: newArr,
          isJson: true,
          isLoading:true
        }).then(res => {
          this.isRepeat = true;
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.readTaskSample(this.sampleQuery);
            this.close()
          }
        })

      },
      // 清空table的多选
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      // 关闭弹框
      close() {
        this.registData = [];
        this.isRepeat = true;
        this.registraDetailShow = false;
        // this.toggleSelection()
      },
      // 下载采样登记表
      downLoadExcel() {
        if (this.multipleSelectionAll.length == 0) {
          this.$notify({
            type: 'warning',
            title: '警告',
            message: '请先勾选样品!'
          });
        } else {
          var arr = [];
          for (var i in this.multipleSelectionAll) {
            arr.push(this.multipleSelectionAll[i].id)
          }
          var data = arr.join(";")
          var url = 'detection/collectionByExcelSample.htm'
          let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
          window.open(process.env.baseUrl + url + '?data=' + data + "&token=" + token);
        }

      },
      // 打印样品标签
      printSample() {
        // console.log(this.multipleSelection)
        if (this.multipleSelection.length == 0) {
          this.$notify({
            title: '警告',
            message: '请先选中样品',
            type: 'warning'
          })
        } else {
          this.printTableShow = true;
          this.acceptOrregist = "regist"
        }

      },
      // 设置分页的大小
      handleSizeChange(val) {
        this.sampleQuery.pageCount = val;
      },
      // 当前是第几页
      handleCurrentChange(val) {
        this.changePageCoreRecordData();
        this.sampleQuery.page = val;
      },
    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .searchitem {
    width: calc(100%/4);
    padding: 0;
    margin-right: 5px;
  }

  .searchitem .informationItem {
    width: calc(100% - 78px);
    float: none;
    margin-left: 8px;
  }
</style>
<style>
  .sampleDialog .el-dialog {
    height: 70%;
  }

  .sampleDialog .el-dialog__body {
    height: calc(100% - 89px);
    padding: 10px;
  }

  .sampleDialog .el-dialog__body tbody tr td:last-child .cell {
    position: relative
  }

  .sampleDialog .el-dialog__body tbody tr td:last-child .cell button {
    position: absolute;
    right: 7%;
  }

  .sampleDialog .el-dialog__body tbody tr .buttonPiluru {
    position: absolute;
    right: 7%;
  }
</style>
